package com.net.model.base.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;

import androidx.annotation.IdRes;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.viewbinding.ViewBinding;

import com.drug.lib.util.StatusBarUtil;
import com.drug.lib.view.CommonTitle;
import com.drug.lib.view.load.LoadPage;
import com.net.model.R;

import me.yokeyword.fragmentation.SupportActivity;

/**
 * 版权：周和权 版权所有
 *
 * @author zhouhequan
 * <p>
 * 创建日期：2022/7/1 or 14:35
 * 描述：
 */
public abstract class BaseLoadVBActivity<VB extends ViewBinding> extends SupportActivity {
    protected VB mBinding = null;
    protected Activity mContext;
    protected RelativeLayout contentView;
    protected LoadPage loadPage;
    protected CommonTitle commonTitle;
    protected FrameLayout fltBaseHead;
    protected FrameLayout fltBaseBottom;
    protected FragmentManager fragmentManager;

    static {
        AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.base_content_activity);
        addContentView();
        saveInstance(savedInstanceState);
        initialize();
        initData();

    }

    private void addContentView() {
        contentView = findViewById(R.id.content_view);
        loadPage = findViewById(R.id.load_page);
        commonTitle = findViewById(R.id.common_title);
        fltBaseHead = findViewById(R.id.flt_base_head);
        fltBaseBottom = findViewById(R.id.flt_base_bottom);
        mBinding = getViewBinding();
        ViewGroup.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
        contentView.addView(mBinding.getRoot(), layoutParams);
        boolean immersive = immersive();
        if (immersive) {
            StatusBarUtil.setImmersiveStatusBar(this, true);
            commonTitle.setImmersive(true);
        }
    }

    protected void saveInstance(Bundle bundle) {
        mContext = this;
        fragmentManager = getSupportFragmentManager();
        preIntent(getIntent());
        getDisplayMetrics();
    }

    protected void preIntent(Intent intent) {

    }

    protected boolean immersive() {
        return false;
    }

    protected abstract VB getViewBinding();

    protected void initialize() {
    }

    protected abstract void initData();


    @Override
    protected void onDestroy() {
        super.onDestroy();
        mBinding = null;
    }

    /**
     * description: 隐藏软键盘
     *
     * @author: zhouhequan
     * @date: 2021/10/25 11:18
     * @Param view:
     * @return: void
     */

    protected void hideSoftInput(EditText view) {
        InputMethodManager mInputMethodManager = (InputMethodManager) getSystemService(this.INPUT_METHOD_SERVICE);
        mInputMethodManager
                .hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    /**
     * description: 打开软键盘
     *
     * @author: zhouhequan
     * @date: 2021/10/25 11:19
     * @Param view:
     * @return: void
     */

    protected void showSoftInput(EditText view) {
        InputMethodManager mInputMethodManager = (InputMethodManager) getSystemService(this.INPUT_METHOD_SERVICE);
        mInputMethodManager
                .showSoftInput(view, InputMethodManager.SHOW_FORCED);
    }

    public int mScreenWidth;
    public int mScreenHeight;
    public float mDensity;

    private void getDisplayMetrics() {
        DisplayMetrics metric = new DisplayMetrics();
        this.getWindowManager().getDefaultDisplay().getMetrics(metric);
        mScreenWidth = metric.widthPixels;
        mScreenHeight = metric.heightPixels;
        mDensity = metric.density;
    }

    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        Configuration config = new Configuration();
        config.setToDefaults();
        res.updateConfiguration(config, res.getDisplayMetrics());
        return res;
    }

    /**
     * description:获取 Handler
     *
     * @author: zhouhequan
     * @date: 2021/10/25 11:19
     * @return: android.os.Handler
     */
    private Handler handler;

    protected final Handler getHandler() {
        if (handler == null) {
            handler = new Handler(getMainLooper());
        }
        return handler;
    }

    /**
     * fragment中添加fragment（add方式）
     *
     * @param target Fragment
     * @param args   Bundle
     */
    protected void startFragment(Fragment target, @IdRes int res, Bundle args) {
        if (args != null)
            target.setArguments(args);
        fragmentManager.beginTransaction()
                .setReorderingAllowed(true)
                .add(res, target)
                .addToBackStack(target.getClass().getSimpleName())
                .commit();
    }

    /**
     * fragment中添加fragment（replace方式）
     *
     * @param target Fragment
     * @param args   Bundle
     */
    protected void replaceFragment(Fragment target, @IdRes int res, Bundle args) {
        target.setArguments(args);
        fragmentManager.beginTransaction()
                .setReorderingAllowed(true)
                .replace(res, target)
                .addToBackStack(target.getClass().getSimpleName())
                .commit();
    }

    /**
     * 清空当前栈所有fragment
     */
    private void clearFragmentStack() {
        int count = fragmentManager.getBackStackEntryCount();
        if (count > 0) {
            FragmentManager.BackStackEntry entry = fragmentManager.getBackStackEntryAt(0);
            fragmentManager.popBackStack(
                    entry.getName(),
                    FragmentManager.POP_BACK_STACK_INCLUSIVE
            );
        }
    }

}
